angular.module('SmartCanteenApp.itemsReport', ['ngRoute', 'ngTouch'])

	.config(['$routeProvider', function($routeProvider) {
		$routeProvider.when('/itempreview', { // 新服务中的菜品销售
			templateUrl: 'newReports/itemPreview.html',
			controller: 'itemPreviewCtrl'
		});
	}])
	//餐卡信息列表
	.controller('itemPreviewCtrl', ['$scope', '$timeout', '$filter', function($scope, $timeout, $filter) {
		$('#datepicker').daterangepicker()
		//打印
		$scope.outPrint = function(){
			var html = $("#tb_itemsales")
			$scope.printHtml(html[0].innerHTML);
		}
		$scope.searchDate = $scope.getNowFormatDate() + ' 至 ' + $scope.getNowFormatDate()
		//默认不显示折柱图等具体数据
		$scope.noDetail = true
		//列的隐藏切换
		$scope.heads = [
			{"name":"产品名称","checked":true},
			{"name":"产品类别","checked":true},
			{"name":"产品销售","checked":true},
			{"name":"产品销售额","checked":true},
			{"name":"毛利","checked":true},
			{"name":"毛利率","checked":false},
			{"name":"销售额占比","checked":false},
			{"name":"口味","checked":false},
			{"name":"做法","checked":false},
		]
		//获取基础信息 档口和类别
		$scope.getOptions = function() {
			//档口
			$scope.getReport($scope.reportPath+'commonLittleService/v1/allWindow?canteenId='+$scope.canteenId,'','get',function(data){
				
				$scope.windows = data.data
			})
			//类别
			$scope.getReport($scope.reportPath+'commonLittleService/v1/allCategory?canteenId='+$scope.canteenId,'','get',function(data){
				$scope.category = data.data
			})
			//餐别
			$scope.getReport($scope.reportPath+'commonLittleService/v1/allPeriodTime?canteenId='+$scope.canteenId,'','get',function(data){
				$scope.periods = data.data
			})
//			$scope.windows = [{
//					"window_id": "1",
//					"name": "档口1"
//				},
//				{
//					"window_id": "3",
//					"name": "档口2"
//				},
//				{
//					"window_id": "2",
//					"name": "档口3"
//				},
//				{
//					"window_id": "4",
//					"name": "档口4"
//				},
//			]
//			$scope.category = [{
//					"category_id": "1",
//					"name": "类别1"
//				},
//				{
//					"category_id": "3",
//					"name": "类别2"
//				},
//				{
//					"category_id": "2",
//					"name": "类别3"
//				},
//				{
//					"category_id": "4",
//					"name": "类别4"
//				},
//			]
//			$scope.periods = [{
//					"period_time_id": "1",
//					"name": "早餐"
//				},
//				{
//					"period_time_id": "2",
//					"name": "午餐"
//				},
//				{
//					"period_time_id": "3",
//					"name": "晚餐"
//				},
//			]
		}
		//get canteenId
		if($scope.getCanteenId() != '') {
			$scope.canteenId = $scope.getCanteenId();
			//获取基础数据
			$scope.getOptions()
		}
		$scope.$on('to-child', function(event, data) {
			//获取从父控制器传来的当前选中食堂
			$scope.canteenId = data;
			//获取基础数据
			$scope.getOptions()
		});
		//分页----------------------
		//每页展示数改变时调取此方法
		$scope.change = function(items) {
			console.log(items);
			$scope.pageSize = items; //改变后的每页显示数
			$scope.pages = Math.ceil($scope.data.length / $scope.pageSize); //分页数
			$scope.newPages = $scope.pages > 5 ? 5 : $scope.pages;
			$scope.pageList = [];
			$scope.selPage = 1;
			$scope.items = $scope.data.slice(0, $scope.pageSize);
			//分页要repeat的数组
			for(var i = 0; i < $scope.newPages; i++) {
				$scope.pageList.push(i + 1);
			}
			//设置表格数据源(分页)
			$scope.setData = function() {
				$scope.items = $scope.data.slice(($scope.pageSize * ($scope.selPage - 1)), ($scope.selPage * $scope.pageSize)); //通过当前页数筛选出表格当前显示数据
			}
		}
		//设置表格数据源(分页)
		$scope.setData = function() {
			if($scope.data == [] || $scope.data == undefined || $scope.data == 'undefined') {
				return;
			}
			$scope.items = $scope.data.slice(($scope.pageSize * ($scope.selPage - 1)), ($scope.selPage * $scope.pageSize)); //通过当前页数筛选出表格当前显示数据
		}
		//打印当前选中页索引
		$scope.selectPage = function(page) {
			//不能小于1大于最大
			if(page < 1 || page > $scope.pages) return;
			//最多显示分页数5
			if(page > 2) {
				//因为只显示5个页数，大于2页开始分页转换
				var newpageList = [];
				for(var i = (page - 3); i < ((page + 2) > $scope.pages ? $scope.pages : (page + 2)); i++) {
					newpageList.push(i + 1);
				}
				$scope.pageList = newpageList;
			}
			$scope.selPage = page;
			$scope.setData();
			$scope.isActivePage(page);
			console.log("选择的页：" + $scope.selPage);
		};

		//设置当前选中页样式
		$scope.isActivePage = function(page) {
			return $scope.selPage == page;
		};
		//上一页
		$scope.Previous = function() {
			$scope.selectPage($scope.selPage - 1);
		}
		//下一页
		$scope.Next = function() {
			$scope.selectPage($scope.selPage + 1);
		};
		//初始条码
		$scope.pageList = [1];
		//初始每页查询数量
		$scope.initial = "10";
		//表格分页数据处理
		$scope.pagination = function(datas) {
			//              	console.log(datas);
			$scope.data = datas;
			//总条目数
			if(datas != null) {
				$scope.totalNums = $scope.data.length;
				//分页总数
				$scope.pageSize = 10;
				$scope.pages = Math.ceil($scope.data.length / $scope.pageSize); //分页数
				$scope.newPages = $scope.pages > 5 ? 5 : $scope.pages;
				$scope.pageList = [];
				$scope.selPage = 1;
				$scope.page = 1
				$scope.items = $scope.data.slice(0, $scope.pageSize);
				//						console.log($scope.items);
				//分页要repeat的数组
				for(var i = 0; i < $scope.newPages; i++) {
					$scope.pageList.push(i + 1);
				}
			}

		}
		//-----------结束分页---------------------|
		//-----------排序  -----------------------|
		$scope.sort = ''
		$scope.desc = undefined
		$scope.sortBy = function(sort) {
			$scope.sort = sort
			$scope.desc = !$scope.desc
			$scope.allItem = $filter('orderBy')($scope.original, [sort], $scope.desc)
			$scope.pagination($scope.allItem)
		}
		//--------结束排序------------------------|
		//发送条件查询
		$scope.searchItem = {
			"window": "",
			"category": ""
		}
		$scope.searchSaleList = function() {
			var datearr = $scope.searchDate.split(' 至 ')
			if($scope.searchItem.window == null || $scope.searchItem.category == null) {
				$scope.searchItem = {
					"window": "",
					"category": ""
				}
			}
			var url = $scope.reportPath + 'itemSaleService/v1/pc/selectItemSale?startDate=' + datearr[0] + '&endDate=' + datearr[1] + '&canteenId=' + $scope.canteenId + '&windowId=' + $scope.searchItem.window + '&categoryId=' + $scope.searchItem.category
			$scope.getReport(url,'','get',function(data){
				$scope.allItem = data.data.item_array
				$scope.sale_number_total = data.data.sale_number_total
				$scope.sale_money_total = data.data.sale_money_total
				$scope.original = data.data.item_array.concat()
				$scope.pagination($scope.allItem)
			})
//			$scope.totalNum = 10
//			$scope.totalMoney = 10
//			$scope.allItem = [{
//					"item_id": "1",
//					"item_name": "菜品1",
//					"category_id": "1",
//					"category_name": "类别1",
//					"sale_number": 1,
//					"sale_money": 1
//				},
//				{
//					"item_id": "2",
//					"item_name": "菜品2",
//					"category_id": "2",
//					"category_name": "类别2",
//					"sale_number": 2,
//					"sale_money": 4
//				},
//				{
//					"item_id": "3",
//					"item_name": "菜品3",
//					"category_id": "2",
//					"category_name": "类别2",
//					"sale_number": 2,
//					"sale_money": 3
//				},
//				{
//					"item_id": "4",
//					"item_name": "菜品4",
//					"category_id": "2",
//					"category_name": "类别2",
//					"sale_number": 3,
//					"sale_money": 2
//				},
//				{
//					"item_id": "5",
//					"item_name": "菜品5",
//					"category_id": "2",
//					"category_name": "类别2",
//					"sale_number": 3,
//					"sale_money": 5
//				},
//				{
//					"item_id": "6",
//					"item_name": "菜品6",
//					"category_id": "2",
//					"category_name": "类别2",
//					"sale_number": 4,
//					"sale_money": 6
//				},
//			]
//			$scope.original = $scope.allItem.concat()
//			$scope.pagination($scope.allItem)
			console.log($scope.items)
		}
		//模糊查询
		$scope.search = {
			"itemName": ""
		}
		$scope.$watch('search.itemName', function() {
			if($scope.search.itemName == undefined) {
				$scope.search.itemName = '';
			}
			//准备一个空的数组
			var newList = [];
			var arr = $scope.original;
			if(arr == undefined)
				return

			var length = arr.length;
			for(var i = 0; i < length; i++) {
				if(arr[i].item_name.indexOf($scope.search.itemName) >= 0) {
					newList.push(arr[i]);
				}
			}
			$scope.pagination(newList);
		})
		//调取详情
		$(".modal-dialog").draggable(); //为模态对话框添加拖拽
		$(".modal").css("overflow", "hidden"); //禁止模态对话框的半透明背景滚动
		$scope.showItemDetail = function(item) {
			$scope.modelItemName = item.item_name
			if(item.item_id == $scope.itemId){
				$scope.noDetail = false
			}else{
				$scope.noDetail = true
			}
			$scope.getItemDate(item.item_id)
			
			
		}
		//查询菜品时间段
		$scope.getItemDate = function(id) {
			$scope.itemId = id
			var url = $scope.reportPath + 'itemSaleService/v1/pc/selectItemTime?itemId=' + id
			$scope.getReport(url,'','get',function(data){
				$scope.dates = data.data.date_array
				$scope.end = $scope.dates.length - 1
				$scope.index = $scope.dates.length - 1
				$scope.date = $scope.dates[$scope.index]
				
				if($scope.dates.length == 0 ){
					$scope.showError('暂无数据')
				}else{
					$('#detailModal').modal('toggle')
				}
			})
//			$scope.dates = ["2017-08-02", "2017-08-03", "2017-08-04", "2017-08-07", "2017-08-08"]
//			$scope.end = $scope.dates.length - 1
//			$scope.index = $scope.dates.length - 1
//			$scope.date = $scope.dates[$scope.index]
		}
		//切换时间区间按钮
		//1.1 前一天
		$scope.previousDate = function() {
			$scope.index = $scope.index - 1
			$scope.date = $scope.dates[$scope.index]
		}
		//1.2 后一天
		$scope.nextDate = function() {
			$scope.index = $scope.index + 1
			$scope.date = $scope.dates[$scope.index]
		}
		//发起查询折柱图等请求
		//1. 初始化数据
		$scope.searchParams = {
			"item_id": "",
			"date": "",
			"period_id": "",
			"interval": "30"
		}

		//2.发起请求
		$scope.getItemDetail = function() {
			$scope.searchParams.item_id = $scope.itemId
			$scope.searchParams.date = $scope.date
			if($scope.searchParams.period_id == '') {
				$scope.showError('请选择餐别！')
				return
			} else {
				var url = $scope.reportPath + 'itemSaleService/v1/pc/selectOneItemCellDetail?itemId=' + $scope.searchParams.item_id + '&date=' + $scope.searchParams.date + '&periodTimeId=' + $scope.searchParams.period_id + '&timeInterval=' + $scope.searchParams.interval
					$scope.getReport(url,'','get',function(data){
						$scope.drawDetail(data.data)
						$scope.mockdata = data.data
						$('#evaluate').val($scope.mockdata.evaluation_index)
						$('#sold').val($scope.mockdata.sale_index)
						$('#evaluate').rating({
							min: 0,
							max: 5,
							step: 0.1,
		
							size: 'xs',
							showClear: false,
							showCaption: false,
						});
						$('#sold').rating({
							min: 0,
							max: 5,
							step: 0.1,
							size: 'xs',
							showClear: false,
							showCaption: false
						});
						$scope.drawDetail($scope.mockdata)
					})
				//------------mock--------------
//				$scope.mockdata = {
//					"item_id": "1",
//					"item_name": "菜品1",
//					"evaluation_index": 3.5,
//					"sale_index": 5,
//					"sale_number": 1,
//					"sale_number_ranking": 1,
//					"sale_money": 1,
//					"sale_money_ranking": 1,
//					"sale_number_passage": [
//						1,
//						200,
//						300
//					],
//					"else_sale_number_passage": [
//						10,
//						200,
//						300
//					],
//					"sale_money_passage": [
//						2,
//						200,
//						300
//					],
//					"sale_time_passage": [
//						"08:00-08:30",
//						"08:30-09:00",
//						"09:00-09:15"
//					],
//					"sale_start_time": "08:00",
//					"sale_end_time": "20:00",
//					"manufacturing_plan_number": 1,
//					"make_number": 1,
//					"residue_number": 1,
//					"item_together": [{
//							"item_id": "",
//							"item_name": "土豆丝",
//							"item_together_cell_number": 1
//						},
//						{
//							"item_id": "",
//							"item_name": "茄子丝",
//							"item_together_cell_number": 1
//						},
//						{
//							"item_id": "",
//							"item_name": "黄瓜丝",
//							"item_together_cell_number": 1
//						}
//					]
//				}
				//---------end mock
//				$('#evaluate').val($scope.mockdata.evaluation_index)
//				$('#sold').val($scope.mockdata.sale_index)
//				$('#evaluate').rating({
//					min: 0,
//					max: 5,
//					step: 0.1,
//
//					size: 'xs',
//					showClear: false,
//					showCaption: false,
//				});
//				$('#sold').rating({
//					min: 0,
//					max: 5,
//					step: 0.1,
//					size: 'xs',
//					showClear: false,
//					showCaption: false
//				});
//				$scope.drawDetail($scope.mockdata)
			}
		}
		//星级 1评价 2售卖
		$scope.drawDetail = function(data) {
			console.log(data)
			//取消遮盖版
			if(data != null){
				$scope.noDetail = false
			}
			//折柱图
			// 基于准备好的dom，初始化echarts实例

			var myChart = echarts.init(document.getElementById('chart'));
			app.title = '多 Y 轴示例';
			var colors = ['#5793f3', '#d14a61', '#675bba'];

			option = {
				color: colors,

				tooltip: {
					trigger: 'axis',
					axisPointer: {
						type: 'cross'
					}
				},
				grid: {
					right: '20%'
				},
				toolbox: {
					feature: {
						dataView: {
							show: true,
							readOnly: false
						},
						magicType: {
							show: true,
							type: ['line', 'bar']
						},
						restore: {
							show: true
						},
						saveAsImage: {
							show: true
						}
					},
					showTitle:false
				},
//				dataRange: {
//			        x: 'center',                 // 水平安放位置，默认为全图左对齐，可选为：
//			                                   // 'center' ¦ 'left' ¦ 'right'
//			                                   // ¦ {number}（x坐标，单位px）
//			        y: 'bottom',               // 垂直安放位置，默认为全图底部，可选为：
//			                                   // 'top' ¦ 'bottom' ¦ 'center'
//			                                   // ¦ {number}（y坐标，单位px）
//			    },
				legend: {
					data: [data.item_name, '总销量', '总营业额']
				},
				xAxis: [{
					type: 'category',
					axisTick: {
						alignWithLabel: true
					},
					data: data.sale_time_passage
				}],
				yAxis: [{
						type: 'value',
						name: data.item_name,
						min: 0,
//						interval: 50, //间隔
//						max: 250,
						position: 'left',
						axisLine: {
							lineStyle: {
								color: colors[0]
							}
						},
						splitLine: {
							show: false //不显示横线格
						},
						axisLabel: {
							formatter: '{value}份'
						}
					},
					{
						type: 'value',
						name: '总销量',
						min: 0,
						position: 'right',
						offset: 80,
						axisLine: {
							lineStyle: {
								color: colors[1]
							}
						},
						splitLine: {
							show: false
						},
						axisLabel: {
							formatter: '{value}份'
						}
					},
					{
						type: 'value',
						name: '总营业额',
						min: 0,
						position: 'right',
						axisLine: {
							lineStyle: {
								color: colors[2]
							}
						},
						axisLabel: {
							formatter: '{value}元'
						}
					}
				],
				series: [{
						name: data.item_name,
						type: 'bar',
						data: data.sale_number_passage
					},
					{
						name: '总销量',
						type: 'bar',
						yAxisIndex: 1,
						data: data.total_sale_number_passage
					},
					{
						name: '总营业额',
						type: 'line',
						yAxisIndex: 2,
						data: data.total_sale_money_passage
					}
				]
			};
			// 使用刚指定的配置项和数据显示图表。
			myChart.setOption(option);
		}
		//列的调整方法
		$scope.head = ["序号","产品名称","产品类别","产品销售","产品销售额","毛利","毛利率","销售额占比","口味","做法"]
		$scope.stretch = function(){
           			//列宽度调整方法
		            var myTAbId = document.getElementById("tb_itemPreview");
		            var tTD; //用来存储当前更改宽度的Table Cell,避免快速移动鼠标的问题   
		            var wData = {};
		            var unset = myTAbId.rows[0].cells.length - $scope.head.length;//不在headList遍历的列数
		            for (var j = 0; j < myTAbId.rows[0].cells.length; j++) {  
		                myTAbId.rows[0].cells[j].index = j;
		                if(unset - 1<j){
		                    myTAbId.rows[0].cells[j].onmousedown = function (event) {   
		                        //记录单元格    
		                        tTD = this;   
		                        if (event.offsetX > tTD.offsetWidth - 10) {   
		                            tTD.mouseDown = true;   
		                            tTD.oldX = event.clientX;   
		                            tTD.oldWidth = tTD.offsetWidth;   
		                        }    
		                    };   
		                    myTAbId.rows[0].cells[j].onmouseup = function (event) {   
		                        //结束宽度调整   
		                        if (tTD == undefined) tTD = this;   
		                        tTD.mouseDown = false;   
		                        tTD.style.cursor = 'default';   
		                        $scope.head[this.index-unset].width = tTD.width;
		                    };   
		                    myTAbId.rows[0].cells[j].onmousemove = function (event) {   
		                        //更改鼠标样式   
		                        if (event.offsetX > this.offsetWidth - 10)   
		                        this.style.cursor = 'col-resize';      
		                        else   
		                        this.style.cursor = 'default';   
		                        //取出暂存的Table Cell   
		                        if (tTD == undefined) tTD = this;   
		                        //调整宽度   
		                        if (tTD.mouseDown != null && tTD.mouseDown == true) { 
		                            
		                            tTD.style.cursor = 'default';   
		                            if (tTD.oldWidth + (event.clientX - tTD.oldX)>0)   
		                            tTD.width = tTD.oldWidth + (event.clientX - tTD.oldX);   
		                            //调整列宽   
		                            // tTD.style.width = tTD.width;   
		                            tTD.style.cursor = 'col-resize';     
		                            //调整该列中的每个Cell   
		                            myTAbId = tTD; while (myTAbId.tagName != 'TABLE') myTAbId = myTAbId.parentElement;   
		                            for (var k = 0; k < myTAbId.rows.length; k++) {   
		                                myTAbId.rows[k].cells[tTD.cellIndex].width = tTD.width;   
		                            }   
		                        }   
		                    };   
		                }  
		            }
        
           		}
	}])
//	.directive('repeatFinish',[function(){
//   	console.log(11)
//   	 $scope.stretch();
//   	return {
//	        link: function($scope,$element,$attr){
//	            if($scope.$last == true){
//	                $scope.stretch();
//	            }
//	        }
//  	};
//	}]);
	.directive('repeatFinish', function($timeout) {
        return {
            restrict: 'A',
            link: function(scope, element, attr) {
                if(scope.$last === true) {
                    $timeout(function() {
                        scope.stretch()
                    });
                }
            }
        };
    });